package com.yulinlin.authorization.modules.app.service;

import com.yulinlin.authorization.modules.AuthService;
import com.yulinlin.authorization.modules.app.entity.AppUserEntity;
import com.yulinlin.data.core.model.BaseModelSelectWrapper;
import com.yulinlin.jdbc.session.JdbcSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component("app")
public class AppAuthService implements AuthService {


    @Autowired
    protected JdbcSession sqlSession;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private UserDetails loadUser(AppUserEntity user){
        UserDetails val  =   User.builder()
                .username(user.getId())
                .password(
                        passwordEncoder.encode(  user.getPassword())
                )
                .authorities(Arrays.asList())
                .build();
        return val;
    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        AppUserEntity user =  BaseModelSelectWrapper.newInstance(AppUserEntity.class)
                .eq("username",username)
                .selectOne();

        if(user != null){


            return loadUser(user);
        }else{
            throw new UsernameNotFoundException("用户名：" + username + " 不存在");
        }


    }

    @Override
    public UserDetails loadUserById(String id) throws UsernameNotFoundException {

        AppUserEntity user =  BaseModelSelectWrapper.newInstance(AppUserEntity.class)
                .eq("id",id)
                .selectOne();
        if(user != null){
            return loadUser(user);
        }else{
            throw new UsernameNotFoundException("用户id：" + id + " 不存在");
        }

    }
}
